package org.example.blog.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.util.DigestUtils;

import java.io.UnsupportedEncodingException;
import java.util.UUID;

@Slf4j
public class SecurityUtils {

    String encrypt(String password) throws UnsupportedEncodingException {
        /*生成盐值*/
        String salt = UUID.randomUUID().toString().replace("-","");
        /*md5(salt+password)*/
        String srcretString = DigestUtils.md5DigestAsHex((salt + password).getBytes("UTF-8"));
        /*数据库存储 盐值+密文*/
        String sqlPassword = salt+srcretString;
        return sqlPassword;
    }

    /*
     * 验证
     */
    public static boolean verify(String inputPassword, String finalPassword)  {
        /*用户输入的密码*/
        /*从数据库获取的密码*/
        /*对密文进行分割，获取盐值*/
        if (finalPassword == null || finalPassword.length()!=64) {
            log.error("密码长度出现问题");
            return false;
        }
        String salt = finalPassword.substring(0,32);
        /*再将*/
        String secretString = null;
        try {
            secretString = DigestUtils.md5DigestAsHex((salt + inputPassword).getBytes("UTF-8"));
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
        /*比较新的密文与sqlPasswor中的密文是否相同*/
        boolean result = (salt + secretString).equals(finalPassword);
        return result;
    }

}
